package com.lagou.work.task03.angel.job.impl;

import com.lagou.work.task03.angel.job.JobService;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author：dingyuan
 * @date：2022.4.5 21:15
 * @description：client,master,server角色获取实现
 * @version: 1.0
 */
public class JobServiceImpl implements JobService {
    private static final ExecutorService executorService = Executors.newFixedThreadPool(3);
    private static final String KEY_SERVER_HOST = "server.host";
    private static final String KEY_SERVER_PORT = "server.port";
    private static final String KEY_SERVER_SOCKET = "server.socket";
    private static final String KEY_CLIENT_SOCKET = "client.socket";
    @Override
    public Socket getJobClient(String host, int port) {
        Socket socket = null;
        try {
            socket = new Socket(host, port);
            if ( socket == null) {
                System.out.println("客户端发送失败!!");
                return socket;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return socket;
    }

    @Override
    public ServerSocket getJobServer(int port) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serverSocket;
    }
    @Override
    public Map<String,List<Object>> getJobManageMaster(List<Integer> serverPort, List<Map<String, String>> clientParam) {

        Map<String, List<Object>> map = new HashMap<String, List<Object>>();
        List<Object> serverSocket = new ArrayList<>();
        List<Object> clientSocket = new ArrayList<>();
        try {
            if(serverPort != null) {
                for (Integer port : serverPort) {
                    serverSocket.add(getJobServer(port));
                }
                map.put(KEY_SERVER_SOCKET, serverSocket);
            }
            if(clientParam != null) {
                for (Map<String, String> clientMap : clientParam) {
                    clientSocket.add(getJobClient(clientMap.get(KEY_SERVER_HOST), Integer.valueOf(clientMap.get(KEY_SERVER_PORT))));
                }
                map.put(KEY_CLIENT_SOCKET, clientSocket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
